<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" class="user-bread">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card class="user-card">
      <!-- 搜索和添加区域 -->
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input placeholder="请输入内容" class="input-with-select" v-model.lazy="queryUserParams.query" @input="getUser">
            <el-button slot="append" icon="el-icon-search" @click="getUser">
            </el-button>
          </el-input>
        </el-col>
        <el-col :span="2.3">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
        <el-col :span="2.3">
          <el-button type="info" @click="showUser('')">全部用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户数据表格区域 -->
      <el-table :data="userList" stripe style="width: 100%" border class="user-table">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="changeUserState(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="delUser(scope.row)"></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top-start" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>

        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination :current-page="queryUserParams.pagenum" :page-size="queryUserParams.pagesize" :total="total"
        :page-sizes="[1, 2, 5, 10]" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
        @current-change="handleCurrentChange">
      </el-pagination>
    </el-card>

    <!-- 添加用户的表单区域 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="closeAddDialog">
      <!-- 表单区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的表单区域 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="50%" @close="closeEditDialog">
      <!-- 表单区域 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>

<script>
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value) || value === '') {
        callback()
      } else {
        callback(new Error('请输入合法的邮箱'))
      }
    }
    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value) || value === '') {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      // 获取用户数据的参数对象
      queryUserParams: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 5,
      },
      // 总共的用户数据量
      total: 0,
      // 存放用户数据
      userList: [],
      // 是否展示添加用户的对话框
      addDialogVisible: false,
      // 添加用户表单的数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      // 添加用户表单的验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
        email: [
          { required: false, message: '请输入密码', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: false, message: '请输入密码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      // 是否展示编辑用户的对话框
      editDialogVisible: false,
      // 编辑用户的表单数据
      editForm: { email: '', mobile: '' },
      // 编辑用户的表单验证规则
      editFormRules: {
        email: [
          { required: false, message: '请输入密码', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: false, message: '请输入密码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    // 初始化获取用户数据
    this.getUser()
  },
  methods: {
    // 根据参数获取用户数据列表
    async getUser() {
      // 发送请求
      const { data: res } = await this.$http.get('/users', {
        params: this.queryUserParams,
      })
      // 200则弹出错误信息提示
      if (res.meta.status != 200) {
        return this.$message.error(res.meta.msg)
      }
      // 请求成功,将用户数据赋值给userList
      this.userList = res.data.users
      this.total = res.data.total
      // console.log(this.userList)
    },
    // 监听开关的变化,改变用户状态
    async changeUserState(userInfo) {
      // console.log(userInfo)
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      // 200则弹出错误信息提示
      if (res.meta.status != 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('用户状态更改成功')
    },
    // 每页显示数据大小改变
    handleSizeChange(pagesize) {
      this.queryUserParams.pagesize = pagesize
      this.getUser()
    },
    // 当前页码改变
    handleCurrentChange(pagenum) {
      this.queryUserParams.pagenum = pagenum
      this.getUser()
    },
    // 关闭添加用户的对话框
    closeAddDialog() {
      // 重置表单
      this.$refs.addFormRef.resetFields()
    },
    // 展示添加或删除用户后的搜索结果
    showUser(username) {
      // 根据用户名查询结果
      this.queryUserParams.query = username
      this.getUser()
    },
    // 在添加用户的dialog中,点击确定,添加新用户
    addUser(username) {
      // 表单预验证
      this.$refs.addFormRef.validate(async (valid, noValiObj) => {
        // console.log(valid)
        if (!valid) return
        const { data: res } = await this.$http.post('/users', this.addForm)
        if (res.meta.status != 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success('新用户添加成功')
        // 隐藏添加用户的对话框
        this.addDialogVisible = false
        // 展示新增的用户数据
        this.showUser(this.addForm.username)
      })
    },
    // 点击删除按钮,删除该用户
    async delUser(row) {
      const { id, username } = row
      const delFlag = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (delFlag !== 'confirm') return this.$message.info('已取消删除')
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败！')
      }
      this.$message.success('删除用户成功！')
      // 展示该用户名的搜索结果为空
      this.showUser(username)
    },
    // 点击修改按钮,可以弹出编辑用户的对话框,并渲染数据
    async showEditDialog(id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200)
        return this.$message.error('查询用户信息失败！')
      this.editForm = res.data
      this.editDialogVisible = true
      // console.log(this.editForm)
    },
    // 关闭编辑用户的对话框时重置表单
    closeEditDialog() {
      // 重置表单
      this.$refs.editFormRef.resetFields()
    },
    // 在编辑用户的dialog中,点击确定,编辑用户提交
    editUser() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        // 表单预验证成功
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          { email: this.editForm.email, mobile: this.editForm.mobile }
        )
        // 请求失败情况
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        // 请求成功
        this.editDialogVisible = false
        this.showUser(this.editForm.username)
        this.$message.success('更新用户信息成功')
      })
    },
  },
}
</script>

<style lang="less">
</style>